package com.lqwu.myoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.lqwu.myoj.model.entity.*;
import com.lqwu.myoj.model.enums.JudgeInfoMessageEnum;
import com.lqwu.myoj.model.enums.QuestionSubmitStatusEnum;

import java.util.List;

/**
 * 默认判题策略
 */
public class DefaultJudgeStrategy implements JudgeStrategy{
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        // 获取上下文全部参数
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();      // 代码沙箱返回的执行信息
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();
        // 新建返回的判题信息
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setMemory(judgeInfo.getMemory());
        judgeInfoResponse.setTime(judgeInfo.getTime());
        // 默认判题信息为成功
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.ACCEPTED;
        // 判断输出结果和题目的输出用例数量是否相等
        if (outputList.size() != inputList.size()){
            // 判断结果为答案错误
            judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
            return judgeInfoResponse;
        }
        // 循环对比输出结果和题目的输出用例
        for (int i = 0; i < outputList.size(); i++) {
            String output = outputList.get(i);
            String judgeCaseOutput = judgeCaseList.get(i).getOutput();
            if (!judgeCaseOutput.equals(output)){
                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
                return judgeInfoResponse;
            }
        }
        // 6）修改数据库中的判题结果
        // 获取返回结果的运行信息
        Long memory = judgeInfo.getMemory();
        Long time = judgeInfo.getTime();
        // 获取题目要求的内存和时间限制
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long timeLimit = judgeConfig.getTimeLimit();
        Long memoryLimit = judgeConfig.getMemoryLimit();
        // 判断是否超出时间限制和内存限制
        if (memory > memoryLimit){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
            return judgeInfoResponse;
        }
        if (time > timeLimit){
            judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
            return judgeInfoResponse;
        }
        judgeInfoResponse.setMessage(judgeInfoMessageEnum.getText());
        return judgeInfoResponse;
    }
}
